<template>
 <el-dialog
  :title="`${newData.id ? '修改学科':'新增学科'}`"
  :visible="dialogVisible"
  @close="closeDialog"
  @open="openDialog"
  width="30%">
  <el-form ref="form" size="small" label-width="80px" :model="formModel" :rules="rules">
    <el-form-item label="学科名称" prop="subjectName">
      <el-input v-model="formModel.subjectName" placeholder="请输入学科名称"></el-input>
    </el-form-item>
    <el-form-item label="是否显示" prop="isFrontDisplay">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="formModel.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </el-form-item>
  </el-form>
      <span slot="footer"  style="text-align:right;" >
    <el-button @click="closeDialog()">取 消</el-button>
    <el-button type="primary" @click="submit">确 定</el-button>
  </span>
</el-dialog>
</template>
<script>
import { update, add } from '@/api/hmmm/subjects'
export default {
  name: 'SubjectsAdd',
  props: {
    newData: {
      type: Object,
      required: true
      // default: () => {}
    }
  },
  data () {
    return {
      formModel: {
        id: null,
        subjectName: null,
        isFrontDisplay: 1
      },
      dialogVisible: false,
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', tirgger: 'blur' }
        ],
        isFrontDisplay: [
          { type: 'number', message: '请选择是否显示', tirgger: 'blur' }
        ]
      }
    }
  },

  methods: {
    openDialog () {
      this.dialogVisible = true
      if (this.newData.id) {
        this.formModel = { ...this.newData }
      } else {
        this.formModel = {
          id: null,
          subjectName: null,
          isFrontDisplay: 1
        }
      }
      // 清除校验效果
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    submit () {
      // console.log(88)
      this.$emit('openDialog')
      this.$refs.form.validate(async (flag) => {
        // console.log(this.data.id)
        if (flag) {
          // console.log()
          if (!this.newData.id) {
            // 新增学科
            await add(this.formModel)
          } else {
            // 修改
            // console.log(1)
            this.formModel.id = this.newData.id
            const arr = await update(this.formModel)
            this.formModel = arr
          }
          this.$message.success('操作成功')
          this.closeDialog()
          this.$emit('update')
        }
      })
    },
    // 关闭对话框
    closeDialog () {
      this.$refs.form.resetFields()
      this.dialogVisible = false
    }
  }

}
</script>
<style scoped lang='less'>
</style>
